Tack.Menu = new Class({
	initialize: function (items) {
		this.items = items;
		this.visible = false;

		document.addEvent('click', this.hide.bindWithEvent(this));

		Tack.Menu.menus.push(this);
	},

	attach: function (element, bind, args) {
		element.addEvent('click', this.show.bindWithEvent(this, [bind, args]));
	},

	buildMenu: function (items, e, bind, args) {
		var ul = new Element('ul');

		$each(items, function (item, text) {
			var li = new Element('li', {
				events: {
					mouseenter: function () { this.addClass('hover'); },
					mouseleave: function () { this.removeClass('hover'); }
				}
			});

			switch ($type(item)) {
				case 'function':
					var a = new Element('a', { href: '#', text: text });
					a.addEvent('click', (function (e) { e.stop(); this.hide(e); item.apply(this.bind, this.args || []); }).bindWithEvent(this));
					li.adopt(a);

					break;
				case 'object':
					li.addClass('sub-menu');
					li.adopt(new Element('span', { text: text }));
					li.adopt(this.buildMenu(item, e, bind, args));

					break;
			}

			ul.adopt(li);
		}, this);

		return ul;
	},

	hide: function (e) {
		if (this.visible) {
			this.visible = false;
			this.element.remove();
			this.element.getElements('li').removeClass('hover');
		}
	},

	show: function (e, bind, args) {
		e.stop();

		Tack.Menu.menus.each(function (m) {
			if (m != this) m.hide();
		}, this);

		this.bind = bind;
		this.args = args;

		if (!this.element) {
			this.element = this.buildMenu(this.items, e, bind, args);
			this.element.addClass('menu');
		}

		this.element.set({ styles: { left: e.page.x, position: 'absolute', top: e.page.y } });
		$(document.body).adopt(this.element);

		this.visible = true;
	}
});

Tack.Menu.menus = [];
